package com.scsj.supermarket.view.activity.serchmodel;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.SearchResultAdapter;
import com.scsj.supermarket.adapter.SelectAllMarkAdapter;
import com.scsj.supermarket.adapter.SelectMarkAdapter;
import com.scsj.supermarket.base.SearchBase;
import com.scsj.supermarket.bean.SearchResultBean;
import com.scsj.supermarket.bean.TotalOrderBean;
import com.scsj.supermarket.event.FirstEvent;
import com.scsj.supermarket.presenter.SearchResultPresenter;
import com.scsj.supermarket.utils.BaiduMapHelper;
import com.scsj.supermarket.utils.RxBus;
import com.scsj.supermarket.utils.Tool;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 搜索结果页面
 */

public class SearchResultActivity extends BaseActivity implements View.OnClickListener, SearchBase.IView {
    private SearchResultPresenter searchResultPresenter;
    private RecyclerView searchResultRv;
    private List<TotalOrderBean> totalOrderBeans;
    private SearchResultAdapter searchResultAdapter;
    private RelativeLayout allSort;
    private RelativeLayout distanceSort;
    private RelativeLayout soldSort;
    private RelativeLayout selectSort;
    private PopupWindow mPopupWindow;
    private PopupWindow mPopupWindow1;
    private RecyclerView rv_select_mark;
    private RecyclerView rv_allselect_mark;
    private List<String> mDatas;
    private List<String> mallDatas;
    private SelectMarkAdapter selectMarkAdapter;
    private SelectAllMarkAdapter selectAllMarkAdapter;
    private LinearLayout ll_select;
    private LinearLayout pop_select_layout;
    private View mlayoutPay;
    private View mlayoutPay1;
    private FrameLayout trasBg;
    private LinearLayout searchViewLl;
    private EditText searchTextEt, lowPrice, highPrice;
    private SearchResultBean searchResultBean;
    private static final String SORTSYNTHES = "1";
    private static final String SORTGOODCOMMENT = "2";
    private static final String SORTDELIVERY = "3";
    private static final String SORTDISTANCE = "4";
    private static final String SORTSALL = "5";
    private String sortingType = SORTSYNTHES;//排序类型：1、综合排序（初始化页面必选1）；2、好评优先；3、起送价最低；4、距离最近；5、销量最高
    //筛选活动类型:1促销2秒杀3折扣
    private static final String ACTIVITYSALES = "1";
    private static final String ACTIVITYSECKILL = "2";
    private static final String ACTIVITYDISCOUNT = "3";
    private String activityType = null;
    private double floorPrice = 0;
    private double topPrice = 0;

    //第一次进来默认按照综合排序,获取总体数据
    List<SearchResultBean.DataBean> allDataList = new ArrayList<>();
    private String searchText;
    private int allposion ;//记录综合排序上次点击的位置 -1 表示空
    private int sortposion = -1;//记录筛选优惠活动上次点击的位置 -1 表示空
    private TextView search_result_distance_tv;
    private TextView search_result_saler_tv;

    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_search_result);
        initToolbar();
//        setToolbarTitle("zzzz");
        hasBack(true);
        initView();
        initData();
        initListener();


    }

    @Override
    protected void initView() {
        searchResultPresenter = new SearchResultPresenter(this);
        searchResultRv = findViewById(R.id.search_result_rv);
        searchTextEt = findViewById(R.id.search_at);
        searchViewLl = findViewById(R.id.search_for_result_ll);
        /**
         * 综合
         */
        allSort = findViewById(R.id.search_result_complex_rl);
        distanceSort = findViewById(R.id.search_result_distance_rl);
        search_result_distance_tv = findViewById(R.id.search_result_distance_tv);
        //销量最高
        soldSort = findViewById(R.id.search_result_saler_rl);
        search_result_saler_tv = findViewById(R.id.search_result_saler_tv);
        selectSort = findViewById(R.id.search_result_select_rl);
        ll_select = findViewById(R.id.ll_select);
        trasBg = findViewById(R.id.trans_layout);
        pop_select_layout = findViewById(R.id.pop_selectsort_layout);
        mlayoutPay1 = View.inflate(this, R.layout.all_select_pop, null);
        mlayoutPay = View.inflate(this, R.layout.pop_selectsort_layout, null);
        mPopupWindow = new PopupWindow(mlayoutPay1, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        mPopupWindow1 = new PopupWindow(mlayoutPay, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

        searchResultRv.setLayoutManager(new LinearLayoutManager(this));
        searchResultRv.setNestedScrollingEnabled(false);
    }

    @Override
    protected void initListener() {
        allSort.setOnClickListener(this);
        distanceSort.setOnClickListener(this);
        soldSort.setOnClickListener(this);
        selectSort.setOnClickListener(this);
        searchViewLl.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        //初次进来，默认按照综合排序
        BaiduMapHelper
                .getInstance()
                .init(null)
                .params(SearchResultActivity.this)
                .showLocation();

        String keyword = getIntent().getStringExtra("keyword");
        searchTextEt.setText(keyword);
        search(keyword,sortingType,activityType,floorPrice,topPrice);

//        searchResultBean= (SearchResultBean) getIntent().getSerializableExtra("searchResulInfo");
//        Toasty.info(SearchResultActivity.this, "数据来了"+searchResultBean.getStatusCode()).show();
//        allDataList= searchResultBean.getData();
//
//        searchResultRv.setLayoutManager(new LinearLayoutManager(this));
//        searchResultRv.setNestedScrollingEnabled(false);
//        searchResultAdapter = new SearchResultAdapter(allDataList, this);
//        searchResultRv.setAdapter(searchResultAdapter);
        //初次进来，默认按照综合排序

        /**
         * 筛选的弹窗数据
         */
        mDatas = new ArrayList<>();
        mDatas.add("促销商品");
        mDatas.add("秒杀商品");
        mDatas.add("折扣商品");

        /**
         * 综合排序的弹窗
         */
        mallDatas = new ArrayList<>();
        mallDatas.add("综合排序");
        mallDatas.add("好评优先");
        mallDatas.add("起送价最低");

        searchTextEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchText = s.toString().trim();
                Logger.e("searchText==>"+searchText);
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_result_complex_rl:
                //综合排序
                trasBg.setVisibility(View.VISIBLE);
                //弹出筛选下拉列表
                showAllSelectSortWindow();
                break;

            case R.id.search_result_distance_rl:
                //按距离排序
                trasBg.setVisibility(View.GONE);
                mPopupWindow.dismiss();
                mPopupWindow1.dismiss();
                selectAllMarkAdapter.isClearAllMark = true;
                sortingType = SORTDISTANCE;
                allposion = -1;
                search_result_distance_tv.setTextColor(Color.parseColor("#FF314A"));
                search_result_saler_tv.setTextColor(Color.parseColor("#686868"));
                search(searchText,sortingType,activityType,floorPrice,topPrice);
                break;

            case R.id.search_result_saler_rl:
                //按销量排序
                trasBg.setVisibility(View.GONE);
                mPopupWindow.dismiss();
                mPopupWindow1.dismiss();
                selectAllMarkAdapter.isClearAllMark = true;
                sortingType = SORTSALL;
                allposion = -1;
                search_result_saler_tv.setTextColor(Color.parseColor("#FF314A"));
                search_result_distance_tv.setTextColor(Color.parseColor("#686868"));
                search(searchText,sortingType,activityType,floorPrice,topPrice);
                break;

            case R.id.search_result_select_rl:
                //按选择条件排序
                trasBg.setVisibility(View.VISIBLE);
                //弹出筛选下拉列表
                showSelectSortWindow();

                break;
            case R.id.search_for_result_ll:
                //搜索按钮点击
                Logger.e("searchText==>" + searchText);
//                if (TextUtils.isEmpty(searchText)) {
//                    Toasty.info(SearchResultActivity.this, "搜索内容不能为空").show();
//                    return;
//                }
                if (searchText == null)
                    searchText = "";
                search(searchText,sortingType,activityType,floorPrice,topPrice);
                break;
            default:

                break;
        }

    }



    /**
     * 联网搜索
     * @param searchText 搜索的内容
     * @param sortingType 排序类型：1、综合排序（初始化页面必选1）；2、好评优先；3、起送价最低；4、距离最近；5、销量最高
     * @param activityType 筛选活动类型:1促销2秒杀3折扣
     * @param floorPrice 筛选最低价
     * @param topPrice 筛选最高价
     */
    private void search(final String searchText, final String sortingType, final String activityType, final double floorPrice,final double topPrice) {

        BaiduMapHelper
                .getInstance()
                .init(null)
                .params(SearchResultActivity.this)
                .showLocation();

        RxBus.getDefault().toObservable(FirstEvent.class)
                //在io线程进行订阅，可以执行一些耗时操作
                .subscribeOn(Schedulers.io())
                //在主线程进行观察，可做UI更新操作
                .observeOn(AndroidSchedulers.mainThread())
                //观察的对象
                .subscribe(new Action1<FirstEvent>() {
                    @Override
                    public void call(FirstEvent firstEvent) {
                        if (firstEvent.getCode().equals("location")) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("latitude", firstEvent.getLatitude());
                            jsonObject.put("longitude", firstEvent.getLongitude());
                            jsonObject.put("searchName", searchText);
                            jsonObject.put("sortingType", sortingType);
                            jsonObject.put("activityType", activityType);
                            if(floorPrice < 0.00001) {
                                jsonObject.put("floorPrice", floorPrice);
                            }
                            if(topPrice < 0.00001) {
                                jsonObject.put("topPrice", topPrice);
                            }
                            Logger.e("zzzzz");
                            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                            searchResultPresenter.deliverData(body);
                        }
                    }
                });
    }

    private void showAllSelectSortWindow() {
        mPopupWindow1.dismiss();
        //设置背景半透明
        //backgroundAlpha(0.5f);
        rv_allselect_mark = mlayoutPay1.findViewById(R.id.rv_allselect_mark);
        rv_allselect_mark.setLayoutManager(new LinearLayoutManager(this));
        selectAllMarkAdapter = new SelectAllMarkAdapter(this, mallDatas, allposion);
        rv_allselect_mark.setAdapter(selectAllMarkAdapter);
        mPopupWindow.showAsDropDown(ll_select);
        mPopupWindow.setOnDismissListener(new SearchResultActivity.popupDismissListener());
        mPopupWindow.setFocusable(true);

        RxBus.getDefault().toObservable(FirstEvent.class)
                //在io线程进行订阅，可以执行一些耗时操作
                .subscribeOn(Schedulers.io())
                //在主线程进行观察，可做UI更新操作
                .observeOn(AndroidSchedulers.mainThread())
                //观察的对象
                .subscribe(new Action1<FirstEvent>() {
                    @Override
                    public void call(FirstEvent firstEvent) {
                        if (firstEvent.getCode().equals("selectItem")) {
                            String selectItem = firstEvent.getTitle();
                            if("综合排序".equals(selectItem)){
                                sortingType = SORTSYNTHES;
                            }else if("好评优先".equals(selectItem)){
                                sortingType = SORTGOODCOMMENT;
                            }else if("起送价最低".equals(selectItem)){
                                sortingType = SORTDELIVERY;
                            }else {
                                sortingType = "1";
                            }
                            search(searchText,sortingType,activityType,floorPrice,topPrice);
                            allposion = selectAllMarkAdapter.currentPosition;
                            search_result_distance_tv.setTextColor(Color.parseColor("#686868"));
                            search_result_saler_tv.setTextColor(Color.parseColor("#686868"));
                            mPopupWindow.dismiss();
                            mPopupWindow1.dismiss();
                        }
                    }
                });
    }

    private void showSelectSortWindow() {
        mPopupWindow.dismiss();
        //设置背景半透明
        // backgroundAlpha(0.5f);
        rv_select_mark = mlayoutPay.findViewById(R.id.rv_select_mark);
        rv_select_mark.setLayoutManager(new GridLayoutManager(this, 3));
        selectMarkAdapter = new SelectMarkAdapter(this, mDatas, sortposion);
        rv_select_mark.setAdapter(selectMarkAdapter);
        mPopupWindow1.showAsDropDown(ll_select);
        mPopupWindow1.setFocusable(true);
        mPopupWindow1.setOnDismissListener(new SearchResultActivity.popupDismissListener());

        //最低价和最高价
        lowPrice = mlayoutPay.findViewById(R.id.low_price);
        highPrice = mlayoutPay.findViewById(R.id.high_price);

        /**
         * 点击弹窗搜索按钮
         */
        final TextView search_btn = mlayoutPay.findViewById(R.id.search_btn);
        search_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (TextUtils.isEmpty(lowPriceText)||TextUtils.isEmpty(highPriceText)){
//                    Toasty.info(SearchResultActivity.this,"请至少选择一项筛选条件").show();
//                    return;
//                }
                if(SelectMarkAdapter.selectMark == null){
                    activityType = null;
                }else if("促销商品".equals(SelectMarkAdapter.selectMark)){
                    activityType = ACTIVITYSALES;
                }else if("秒杀商品".equals(SelectMarkAdapter.selectMark)){
                    activityType = ACTIVITYSECKILL;
                }else if("折扣商品".equals(SelectMarkAdapter.selectMark)){
                    activityType = ACTIVITYDISCOUNT;
                }else {
                    activityType = null;
                }
                if(lowPrice.getText() == null || lowPrice.getText().toString().trim().length() == 0) {
                    floorPrice = 0;
                }else {
                    floorPrice = Double.valueOf(lowPrice.getText().toString().trim());
                }
                if(highPrice.getText() == null || highPrice.getText().toString().trim().length() == 0){
                    topPrice = 0;
                }else {
                    topPrice = Double.valueOf(highPrice.getText().toString().trim());
                }
                search(searchText,sortingType,activityType,floorPrice,topPrice);
                sortposion = selectMarkAdapter.currentPosition;
                mPopupWindow.dismiss();
                mPopupWindow1.dismiss();
            }
        });

        /**
         * 点击弹窗清空按钮
         */
        TextView cancel_btn = mlayoutPay.findViewById(R.id.cancel_btn);
        cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //清空最低价和最高价
                lowPrice.setText("");
                highPrice.setText("");
                Toasty.info(SearchResultActivity.this, "点击清空按钮").show();
                //清空选择的标签
                SelectMarkAdapter.isClearAllMark = true;
                selectMarkAdapter.notifyDataSetChanged();
            }
        });


    }



    @Override
    public void showSuccessMsg(String s, SearchResultBean searchResultBean) {
        Logger.e("zzz");
        if (searchResultBean.getData() == null || searchResultBean.getData().size() == 0) {
//            Toasty.success(SearchResultActivity.this, "未搜索到商品").show();
            Logger.e("zzz未搜索到商品");
        } else {
            String s1 = new Gson().toJson(searchResultBean);
            searchResultAdapter = new SearchResultAdapter(searchResultBean.getData(), this);
            searchResultRv.setAdapter(searchResultAdapter);
//            Toasty.success(SearchResultActivity.this, "搜索结果出来了").show();
            Logger.e("zzz搜索结果出来了");
            Logger.json(s1);
        }

    }

    @Override
    public void showErrorMsg(String s) {
        Toasty.error(SearchResultActivity.this, s).show();
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        this.getWindow().setAttributes(lp);
    }

    /**
     * 将背景透明度改回来
     */
    class popupDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }

    }
}
